package com.fhnew.app.ui.activity.userinfo.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fhnew.app.R;
import com.fhnew.app.global.Constants;
import com.fhnew.app.model.CustomObserver;
import com.fhnew.app.model.internet.model.ThirdGameModel;
import com.fhnew.app.model.internet.model.UserModel;
import com.fhnew.app.model.network.HttpJsonUtils;
import com.fhnew.app.model.network.entity.req.ResALLGames;
import com.fhnew.app.util.OnItemClickListener;
import com.fhnew.app.util.StringUtil;
import com.fhnew.app.widget.LoadingDialog;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;

import java.util.ArrayList;
import java.util.LinkedList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2019/9/12.
 */

public class MycodeFragment extends Fragment {


    private TextView moneytext;
    private TextView balance1;
    private NiceSpinner spinner;
    private RecyclerView usergamelist;
    private Adapter adapter;

    private ArrayList<ResALLGames.DataBean> usergamedata = new ArrayList<>();

    private LoadingDialog loadingDialog;

    private void initView (View view) {

        loadingDialog = new LoadingDialog((LinearLayout) view);
        loadingDialog.setDialogCancelable(false);
        loadingDialog.setShowTips(false);


        moneytext = view.findViewById(R.id.moneytext);
        balance1 = view.findViewById(R.id.balance1);
        spinner = view.findViewById(R.id.spinner);
        usergamelist = view.findViewById(R.id.usergamelist);

        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4, LinearLayoutManager.VERTICAL, false);
        usergamelist.setLayoutManager(layoutManager);
        adapter = new Adapter();
        usergamelist.setAdapter(adapter);

        spinner.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
            @Override
            public void onItemSelected (NiceSpinner parent, View view, int position, long id) {
                spinnerSelectId = usergamedata.get(position).game_id;
                balance1.setText(thirdGameModel.getMoney(spinnerSelectId, true));
                StringUtil.format(balance1);
            }
        });
    }

    private void initInfoView () {
        if (thirdGameModel.isGameListRequesting()) {
            loadingDialog.showLoading();
        }
        moneytext.setText(UserModel.user.money);

        adapter.notifyDataSetChanged();
    }


    @Nullable
    @Override
    public View onCreateView (@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        container = (ViewGroup) inflater.inflate(R.layout.mycodelayout, null);
        initView(container);
        initInfo();
        return container;
    }

    @Override
    public void onResume () {
        super.onResume();
        initInfoView();
    }

    @Override
    public void onHiddenChanged (boolean hidden) {
        super.onHiddenChanged(hidden);
        getusergamedata();
    }

    @Override
    public void onDestroyView () {
        super.onDestroyView();
        userModel.unRegistListener(userInformationChanged);
        thirdGameModel.unregistThirdGameMoneyChangedListener(thirdGameMoneyChangedListener);
    }

    private UserModel.UserInformationChanged userInformationChanged = new UserModel.UserInformationChanged() {
        @Override
        public void userInformationChanged () {

        }
    };

    private ThirdGameModel.ThirdGameMoneyChangedListener thirdGameMoneyChangedListener = new ThirdGameModel.ThirdGameMoneyChangedListener() {

        @Override
        public void myMoneyChanged () {
            moneytext.setText(userModel.getUser().getMoney());
            StringUtil.format(balance1);
        }

        @Override
        public void allThirdGameMoneyChanged () {
            for (int i = 0; i < usergamedata.size(); i++) {
                usergamedata.get(i).money = thirdGameModel.getMoney(usergamedata.get(i).game_id, false);
            }

            balance1.setText(thirdGameModel.getMoney(spinnerSelectId, false));
            StringUtil.format(balance1);
            adapter.notifyDataSetChanged();

            loadingDialog.dismiss();
        }

        @Override
        public void thirdGameMoneyChanged (int game_id) {

        }
    };

    //===================================================================================

    private UserModel userModel;
    private ThirdGameModel thirdGameModel;

    private int spinnerSelectId;

    private void initInfo () {
        userModel = UserModel.getInstance(getContext());
        userModel.registListener(userInformationChanged);

        thirdGameModel = ThirdGameModel.getInstance(getContext());
        thirdGameModel.registThirdGameMoneyChangedListener(thirdGameMoneyChangedListener);

        getusergamedata();
    }


    //===================================================================================

    private void getusergamedata () {
        HttpJsonUtils.getHttpApiInstance()
                .getallgame(Constants.getuseAdress() + "api/GamesApi/list_2", UserModel.Token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<ResALLGames>() {
                    @Override
                    protected void onCustomNext (ResALLGames resALLGames) {
                        usergamedata.clear();
                        LinkedList<String> data1 = new LinkedList<>();
                        for (int i = 0; i < resALLGames.data.size(); i++) {
                            ResALLGames.DataBean dataBean = new ResALLGames.DataBean();
                            dataBean.name = resALLGames.data.get(i).name;
                            data1.add(dataBean.name);
                            dataBean.game_id = resALLGames.data.get(i).game_id;
                            dataBean.money = thirdGameModel.getMoney(dataBean.game_id, false);
                            usergamedata.add(dataBean);
                        }
                        spinner.attachDataSource(data1);
                        adapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onSubscribeCustom (Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom (Throwable e) {

                    }
                });
    }


    class Adapter extends RecyclerView.Adapter<Adapter.MViewHolder>
            implements OnItemClickListener {
        @NonNull
        @Override
        public Adapter.MViewHolder onCreateViewHolder (@NonNull ViewGroup viewGroup, int viewType) {
            return new Adapter.MViewHolder(LayoutInflater.from(getContext())
                    .inflate(R.layout.usergameitem, viewGroup, false));
        }

        @Override
        public void onBindViewHolder (final Adapter.MViewHolder holder, final int position) {
            holder.usergamemame.setText(usergamedata.get(position).name);

            holder.gameimg.setVisibility(View.GONE);
            holder.usergamemoney.setVisibility(View.VISIBLE);
            holder.usergamemoney.setText(usergamedata.get(position).money);

            StringUtil.format(holder.usergamemoney);


            holder.gameimg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick (View v) {
//                    holder.thirdGameModel.getMoney(spinnerSelectId,true);
                    thirdGameModel.getThirdMoneyChange(usergamedata.get(position).game_id);
                }
            });
            holder.usergamebt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick (View v) {
                    getActivity().finish();
                }
            });
        }

        @Override
        public int getItemCount () {
            return usergamedata.size();
        }

        @Override
        public void onItemClick (View view, int position) {

        }

        public class MViewHolder extends RecyclerView.ViewHolder {
            TextView usergamemame;
            TextView usergamemoney;
            TextView usergamebt;
            ImageView gameimg;

            MViewHolder (View itemView) {
                super(itemView);
                usergamemame = (TextView) itemView.findViewById(R.id.usergamemame);
                usergamemoney = (TextView) itemView.findViewById(R.id.usergamemoney);
                usergamebt = (TextView) itemView.findViewById(R.id.usergamebt);
                gameimg = (ImageView) itemView.findViewById(R.id.gameimg);
            }
        }
    }

}
